package com.intercept.test.service.impl;

import com.intercept.test.common.Constant;
import com.intercept.test.common.ResponseCode;
import com.intercept.test.common.ServerResponse;
import com.intercept.test.exception.ServiceException;
import com.intercept.test.service.TokenService;
import com.intercept.test.util.JedisUtil;
import com.intercept.test.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class TokenServiceImpl implements TokenService {

    private static final String TOKEN_NAME = "token";

    @Autowired
    private JedisUtil jedisUtil;

    @Override
    public ServerResponse createToken() {
        String str = RandomUtil.UUID32();
        StrBuilder token = new StrBuilder();
        token.append(Constant.Redis.TOKEN_PREFIX).append(str);
        //设置过期时间
        jedisUtil.set(token.toString(), token.toString(), Constant.Redis.EXPIRE_TIME_MINUTE);

        return ServerResponse.success(token.toString());
    }

    @Override
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        if (StringUtils.isBlank(token)) {// header中不存在token
            token = request.getParameter(TOKEN_NAME);
            if (StringUtils.isBlank(token)) {// parameter中也不存在token
                throw new ServiceException(ResponseCode.ILLEGAL_ARGUMENT.getMsg());
            }
        }
        // https://juejin.cn/post/6906290538761158670#heading-13
        //执行成功：则说明redis内存中  存在该Token,是第一次调用接口，  允许执行后面业务逻辑。
        //执行失败：则说明redis内存中不存在该Token,是  重复调用接口，不允许执行后面业务逻辑
        if (!jedisUtil.exists(token)) {
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());
        }
        //第一次调用接口后，删除redis中的 这个key
        Long del = jedisUtil.del(token);
        if (del <= 0) {
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());
        }
    }

}
